package com.acme.javaschool.intense.sems.sem2concurrency.pool.clients;

import com.acme.javaschool.intense.sems.sem2concurrency.pool.Pool;
import com.acme.javaschool.intense.sems.sem2concurrency.pool.data.PoolableObject;

import java.util.Random;

import static java.lang.Thread.sleep;

public class ReleaserClient<T> extends GetterClient<T> {

    public int numWork = 3;

    public ReleaserClient(Pool<T> pool) {
        super(pool);
        Random rnd = new Random();
        rnd.setSeed(System.nanoTime());
//        numWork = rnd.nextInt(5) + 1;
        pool.getTestHelper().submitWork(numWork);
    }

    @Override
    public void run() {
        PoolableObject<T> t = null;

        for (int i = 0; i < numWork; i++) {
            t = getPoolableObject();
            work(t);

            if (pause()) break;
        }
    }

    protected void work(PoolableObject<T> t) {
        try {
            pool.release(t);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread() + ": " + e.getMessage());
        }

    }
}

